<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>WebSocket JSON数据发送</title>

    <style>
        #message-container {
            height: 200px;
            overflow-y: scroll;
            border: 1px solid #ccc;
            padding: 10px;
        }
    </style>
</head>
<body>
<h1>WebSocket JSON数据发送</h1>

<button id="sendButton">发送数据</button>

<div id="message-container"></div>
<script>
    const wsUrl = "ws://127.0.0.1:9998/websocket";
    // const userInputs = Array.from({length: 40}, (_, index) => String.fromCharCode(65 + (index % 26))); // 生成 A 到 T 的 40 个输入
    const userInputs = Array.from({length: 40}, (_, index) => index); // 生成 0 到 39 的 40 个输入);
    console.log('userInputs:', userInputs);
    // console.log('userInputs :', userInputs);
    const sendButton = document.getElementById('sendButton');

    sendButton.addEventListener('click', startWebSocketConnections);

    async function startWebSocketConnections() {
        try {
            const websocketPromises = userInputs.map((input, index) => {
                const messageId = "1000" + index;
                return createWebSocketAndSendData(wsUrl, input, messageId);
            });

            const results = await Promise.all(websocketPromises);
            console.log(new Date().toLocaleString(), '所有WebSocket连接已成功发送数据:', results);
        } catch (error) {
            console.error(new Date().toLocaleString(), '发生错误: ', error);
        }
    }

    function createWebSocketAndSendData(url, userInput, messageId) {
        return new Promise((resolve, reject) => {
            const websocket = new WebSocket(url);

            websocket.onopen = function () {
                console.log('WebSocket连接已建立');
                sendJsonData(websocket, userInput, messageId, resolve);

                websocket.onmessage = function (event) {
                    console.log('WebSocket onmessage ', event.data);
                    const messageElement = document.createElement('div');
                    messageElement.textContent = event.data;

                    const messageContainer = document.getElementById('message-container');
                    messageContainer.appendChild(messageElement);
                    messageContainer.scrollTop = messageContainer.scrollHeight;
                };

                websocket.onclose = function (event) {
                    console.log('WebSocket 连接已关闭。');
                };
            };

            websocket.onerror = function (event) {
                reject('WebSocket连接失败');
            };
        });
    }

    function sendJsonData(websocket, userInput, messageId, resolve) {
        const initialData = {
            "code": "invite",
            "messageId": messageId,
            "msg": userInput + "_" + 0,
            "timestamp": new Date().toLocaleString()
        };
        console.log(initialData);
        websocket.send(JSON.stringify(initialData));

        for (let i = 1; i <= 60; i++) {
            const randomRole = Math.round(Math.random());
            const ackData = {
                "code": "ack",
                "messageId": messageId,
                "msg": userInput + "_" + i,
                "role": randomRole,
                "timestamp": new Date().toLocaleString()
            };
            console.log(ackData);
            websocket.send(JSON.stringify(ackData));
        }

        const byeData = {
            "code": "bye",
            "messageId": messageId,
            "msg": userInput + "_" + 0,
            "timestamp": new Date().toLocaleString()
        };
        console.log(byeData);
        websocket.send(JSON.stringify(byeData));
        resolve(`数据发送完成: ${userInput}`);
    }
</script>
</body>
</html>
